<template>
	<view class="station-detail">
		<!-- 头部导航 -->
		<view class="header">
			<view class="header-left" @click="goBack">
				<text class="back-icon">‹</text>
			</view>
			<view class="header-center">
				<text class="station-name">{{ stationName }}</text>
				<text class="station-code">{{ stationCode }}</text>
			</view>
		</view>

		<!-- 近三日雨量卡片 -->
		<view class="info-card">
			<view class="card-header">
				<text class="card-title">近三日雨量</text>
				<text class="update-time">{{ getCurrentTime() }}</text>
			</view>
			<view class="card-content">
				<view class="recent-rainfall-list">
					<view 
						v-for="(item, index) in recentRainfallData" 
						:key="index"
						class="rainfall-item"
					>
						<text class="rainfall-period">{{ item.period }}</text>
						<text class="rainfall-amount">降雨量：{{ item.amount }}mm</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 测站降雨卡片 -->
		<view class="info-card">
			<view class="card-header">
				<text class="card-title">测站降雨</text>
			</view>
			<view class="card-content">
				<!-- 时间选择器 -->
				<view class="simple-date-bar">
					<DateTimePicker 
						v-model="startDate" 
						:defaultDaysOffset="-1"
						@change="onStartDateChange"
					/>
					<text class="date-separator">至</text>
					<DateTimePicker 
						v-model="endDate" 
						:defaultDaysOffset="0"
						@change="onEndDateChange"
					/>
				</view>

				<!-- 降雨柱状图 -->
				<!-- #ifdef H5 -->
				<view class="chart-scroll-container" style="height: 410px; padding-bottom: 10px;">
					<canvas 
						id="rainfall-line-chart" 
						class="rainfall-line-chart"
						width="2400"
						height="400"
						:style="{ width: '2400px', height: '400px' }"
					></canvas>
				</view>
				<!-- #endif -->
				<!-- #ifndef H5 -->
				<view class="chart-not-supported">
					<text>当前环境不支持图表显示，请在浏览器中查看</text>
				</view>
				<!-- #endif -->

				<!-- 数据表格 -->
				<view class="data-table-section">
					<view class="table-header">
						<text class="table-title">时间</text>
						<text class="table-title">降雨(mm)</text>
						<text class="table-title">累计降雨(mm)</text>
					</view>

					<!-- 折叠展开控制条 -->
					<view class="expand-bar" @click="isTableExpanded = !isTableExpanded">
						<text class="expand-text">无降雨{{ isTableExpanded ? '已展开' : '已折叠' }}</text>
						<text class="expand-action">{{ isTableExpanded ? '收起数据' : '展开数据' }}</text>
						<text class="expand-arrow">{{ isTableExpanded ? '⌃' : '⌄' }}</text>
					</view>

					<view class="table-content">
						<view 
							v-for="(item, index) in chartDataToShow" 
							:key="index"
							class="table-row"
							:class="{ 'even-row': index % 2 === 0 }"
						>
							<text class="table-cell">{{ item.time }}</text>
							<text class="table-cell">{{ item.hasData ? item.value : '-' }}</text>
							<text class="table-cell">{{ item.cumulative !== null ? item.cumulative : '-' }}</text>
						</view>
						<view v-if="chartData.length === 0" class="empty-table">
						<text class="empty-text">暂无降雨数据</text>
					</view>
				</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { API_BASE_URL } from '@/config/api.js'
import DateTimePicker from '@/components/DateTimePicker.vue'

// 页面参数
const stationCode = ref('')
const stationName = ref('')

// 响应式数据
const loading = ref(false)
const chartData = ref([])
const recentRainfallData = ref([])
const isTableExpanded = ref(false) // 表格折叠展开状态

// 时间选择器相关数据
const startDate = ref({ year: '', month: '', day: '', hour: '' })
const endDate = ref({ year: '', month: '', day: '', hour: '' })
const isQuerying = ref(false)


// 页面加载时获取参数
onLoad((options) => {
	console.log('station-detail页面加载，参数:', options)
	
	if (options.stationCode) {
		stationCode.value = decodeURIComponent(options.stationCode)
	}
	
	if (options.stationName) {
		stationName.value = decodeURIComponent(options.stationName)
	}
	
	// 处理时间参数
	if (options.startTime) {
		const startTimeParam = decodeURIComponent(options.startTime)
		console.log('接收到开始时间参数:', startTimeParam)
		
		// 解析时间格式 "YYYY-MM-DD HH:00:00"
		const startTimeParts = startTimeParam.split(' ')
		if (startTimeParts.length === 2) {
			const dateParts = startTimeParts[0].split('-')
			const hourPart = startTimeParts[1].split(':')[0]
			startDate.value = {
				year: dateParts[0],
				month: dateParts[1],
				day: dateParts[2],
				hour: hourPart.padStart(2, '0')
			}
		}
	}
	
	if (options.endTime) {
		const endTimeParam = decodeURIComponent(options.endTime)
		console.log('接收到结束时间参数:', endTimeParam)
		
		// 解析时间格式 "YYYY-MM-DD HH:00:00"
		const endTimeParts = endTimeParam.split(' ')
		if (endTimeParts.length === 2) {
			const dateParts = endTimeParts[0].split('-')
			const hourPart = endTimeParts[1].split(':')[0]
			endDate.value = {
				year: dateParts[0],
				month: dateParts[1],
				day: dateParts[2],
				hour: hourPart.padStart(2, '0')
			}
		}
	}
	
	console.log('解析后的参数:', {
		stationCode: stationCode.value,
		stationName: stationName.value,
		startDate: startDate.value,
		endDate: endDate.value
	})
})

// 获取当前时间
const getCurrentTime = () => {
	const now = new Date()
	const year = now.getFullYear()
	const month = String(now.getMonth() + 1).padStart(2, '0')
	const day = String(now.getDate()).padStart(2, '0')
	const hour = String(now.getHours()).padStart(2, '0')
	const minute = String(now.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hour}时`
}

// 查询事件处理
const handleQueryButtonClick = () => {
	if (isQuerying.value) return
	// 使用用户选择的时间范围，不传参数使用默认的startDate和endDate
	queryStationData()
}

// 时间选择器事件处理
const onStartDateChange = (value) => {
	console.log('开始时间变更:', value)
	handleQueryButtonClick()
}

const onEndDateChange = (value) => {
	console.log('结束时间变更:', value)
	handleQueryButtonClick()
}

// 格式化日期时间对象为字符串
const formatDateTime = (dateObj) => {
	return `${dateObj.year}-${dateObj.month}-${dateObj.day} ${dateObj.hour}:00:00`
}

// 格式化Date对象为字符串（用于API调用）
const formatDateToString = (date, hour = '00') => {
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hourStr = String(hour).padStart(2, '0')
	return `${year}-${month}-${day} ${hourStr}:00:00`
}

// 判断数据行是否有降雨
const hasRainfallData = (item) => {
	return item && item.hasData && item.value > 0
}

// 获取无降雨记录数量
const getNoDataCount = () => {
	return chartData.value.filter(item => !hasRainfallData(item)).length
}

// 根据折叠状态显示的数据
const chartDataToShow = computed(() => {
	// 展开时显示全部，折叠时只显示有降雨的记录
	return isTableExpanded.value ? chartData.value : chartData.value.filter(hasRainfallData)
})

// 查询测站数据
const queryStationData = async () => {
	if (!stationCode.value) {
		console.warn('必须传递测站编码参数')
		return
	}
	
	try {
		loading.value = true
		chartData.value = []
		
		const startTime = formatDateTime(startDate.value)
		const endTime = formatDateTime(endDate.value)
		
		console.log('正在调用降雨数据API:', {
			stationCode: stationCode.value,
			startTime,
			endTime,
		})
		
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_pptn_by_stcd?stcd=${stationCode.value}&start_time_str=${encodeURIComponent(startTime)}&end_time_str=${encodeURIComponent(endTime)}`,
			method: 'GET'
		})
		
		console.log('降雨数据API响应:', response)
		
		if (response.data.success) {
			const data = response.data.data
			const results = []

			console.warn('API返回的原始数据:', data)
			
			// 处理API返回的数据结构
			for (const [dateTimeKey, records] of Object.entries(data)) {
				console.log('处理时间键:', dateTimeKey, '记录数组:', records)
				if (Array.isArray(records)) {
					records.forEach((record, index) => {
						console.log(`记录 ${index}:`, record)
						// 验证数据有效性
						const isValid = validateRainfallData(record)
						console.log(`记录 ${index} 验证结果:`, isValid)
						if (isValid) {
							const formatted = formatRainfallRecord(record, dateTimeKey)
							console.log(`格式化后的记录 ${index}:`, formatted)
							results.push(formatted)
						}
					})
				}
			}
			
			// 补充缺失的时间节点
			const completeResults = fillMissingTimePoints(results, startTime, endTime)
			
			// 按时间倒序排序（最新时间在前）
			completeResults.sort((a, b) => new Date(b.time) - new Date(a.time))
			
			// 计算累计降雨量 - 需要按时间正序计算，然后保持倒序显示
			// 先创建一个按时间正序的副本用于计算累计值
			const sortedForCumulative = [...completeResults].sort((a, b) => new Date(a.time) - new Date(b.time))
			let cumulative = 0
			sortedForCumulative.forEach(item => {
				if (item.hasData && item.value !== null) {
					// 只有真实数据才参与累计计算
					cumulative += item.value
					item.cumulative = Math.round(cumulative * 10) / 10
				} else {
					// 无数据时累计值保持上一个有效的累计值
					item.cumulative = cumulative > 0 ? Math.round(cumulative * 10) / 10 : null
				}
			})
			
			chartData.value = completeResults
			console.log('处理后的查询结果:', chartData.value)
			
			// 数据加载完成后初始化柱状图
			nextTick(() => {
				setTimeout(() => {
					initRainfallBarChart()
				}, 300)
			})
		} else {
			console.error('API返回失败:', response.data)
			// 清空数据，不生成虚拟数据
			chartData.value = []
		}
	} catch (error) {
		console.error('查询数据失败:', error)
		// 清空数据，不生成虚拟数据
		chartData.value = []
	} finally {
		loading.value = false
	}
}

// 验证降雨数据记录
const validateRainfallData = (record) => {
	// 检查必需字段
	if (!record.stcd) {
		return false
	}
	
	// 检查是否有有效的降雨数据 - 使用 precipitation 字段
	const rainfallFields = ['precipitation']
	
	for (const field of rainfallFields) {
		if (record[field] !== undefined && record[field] !== null) {
			const value = parseFloat(record[field])
			// 检查是否为有效数字，且在合理范围内（0-500mm）
			if (!isNaN(value) && value >= 0 && value <= 500) {
				return true
			}
		}
	}
	
	return false
}

// 格式化降雨数据 - 保留所有有效数据包括0值
const formatRainfallRecord = (record, dateTimeKey) => {
	const precipitation = parseFloat(record.precipitation)
	return {
		time: dateTimeKey,
		value: Math.round(precipitation * 10) / 10, // 保留1位小数
		unit: 'mm',
		stationName: record.station_name || '未知站点',
		stationCode: record.stcd,
		rainfallLevel: getRainfallLevel(precipitation),
		hasData: true // 标识这是真实数据
	}
}

// 获取降雨等级
const getRainfallLevel = (precipitation) => {
	if (precipitation === 0) return '无雨'
	if (precipitation < 10) return '小雨'
	if (precipitation < 25) return '中雨'
	if (precipitation < 50) return '大雨'
	return '暴雨'
}

// 为柱状图提供颜色计算函数
const getChartBarColor = (rainfall) => {
	if (rainfall >= 30) {
		return '#0000FF' // 蓝色 - 30mm以上
	} else if (rainfall > 15) {
		return '#1E90FF' // 道奇蓝 - 15-30mm
	} else if (rainfall > 5) {
		return '#32CD32' // 酸橙绿 - 5-15mm
	} else if (rainfall > 0) {
		return '#90EE90' // 浅绿色 - 0-5mm
	} else {
		return '#E0E0E0' // 灰色 - 无降雨
	}
}

// 补充缺失的时间节点
const fillMissingTimePoints = (existingData, startTimeStr, endTimeStr) => {
	console.log('fillMissingTimePoints: 开始补充时间节点', {
		existingDataCount: existingData.length,
		startTime: startTimeStr,
		endTime: endTimeStr
	})
	
	// 解析开始和结束时间
	const startTime = new Date(startTimeStr)
	const endTime = new Date(endTimeStr)
	
	// 创建现有数据的时间映射 - 使用更灵活的时间匹配
	const dataMap = new Map()
	existingData.forEach(item => {
		// 标准化时间格式，只保留到小时
		const itemTime = new Date(item.time)
		const timeKey = `${itemTime.getFullYear()}-${String(itemTime.getMonth() + 1).padStart(2, '0')}-${String(itemTime.getDate()).padStart(2, '0')} ${String(itemTime.getHours()).padStart(2, '0')}:00:00`
		dataMap.set(timeKey, item)
	})
	
	console.log('fillMissingTimePoints: 现有数据时间映射', Array.from(dataMap.keys()))
	
	// 生成完整的时间序列（每小时一个点）
	const completeData = []
	const currentTime = new Date(startTime)
	
	while (currentTime <= endTime) {
		// 生成标准化的时间键
		const timeKey = `${currentTime.getFullYear()}-${String(currentTime.getMonth() + 1).padStart(2, '0')}-${String(currentTime.getDate()).padStart(2, '0')} ${String(currentTime.getHours()).padStart(2, '0')}:00:00`
		
		if (dataMap.has(timeKey)) {
			// 如果存在数据，使用原始数据
			const existingItem = dataMap.get(timeKey)
			completeData.push({
				...existingItem,
				time: timeKey, // 统一时间格式
				hasData: true // 标识有真实数据
			})
		} else {
			// 如果不存在数据，创建一个无数据的数据点
			completeData.push({
				time: timeKey,
				value: null, // 使用null表示无数据
				unit: 'mm',
				stationName: stationName.value || '未知站点',
				stationCode: stationCode.value,
				rainfallLevel: '无数据',
				cumulative: null, // 累计值也设为null，会在后续重新计算
				hasData: false // 标识无数据
			})
		}
		
		// 增加1小时
		currentTime.setHours(currentTime.getHours() + 1)
	}
	
	console.log('fillMissingTimePoints: 补充完成', {
		originalCount: existingData.length,
		completeCount: completeData.length,
		sampleTimes: completeData.slice(0, 5).map(item => item.time)
	})
	
	return completeData
}

// 获取近三日雨量数据（仅用于统计显示）
const getRecentRainfallData = async () => {
	// 获取今天8点作为结束时间
	const today8AM = new Date()
	// 从今天8点往前数3天作为开始时间
	const threeDaysAgo8AM = new Date(today8AM)
	threeDaysAgo8AM.setDate(today8AM.getDate() - 3)
	
	try {
		// 调用API获取三天内的统计数据
		const startTime = formatDateToString(threeDaysAgo8AM, '08')
		const endTime = formatDateToString(today8AM, '08')
		
		console.log('正在获取近三日统计数据:', {
			stationCode: stationCode.value,
			startTime,
			endTime,
		})
		
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_pptn_by_stcd?stcd=${stationCode.value}&start_time_str=${encodeURIComponent(startTime)}&end_time_str=${encodeURIComponent(endTime)}`,
			method: 'GET'
		})
		
		console.log('近三日统计API返回数据:', response.data)
		
		if (response.data.success) {
			// 处理API返回的数据，按天统计
			const data = response.data.data
			const dailyStats = {}
			
			console.log('开始处理近三日数据:', data)
			
			// 按天分组统计降雨量
			for (const [dateTimeKey, records] of Object.entries(data)) {
				console.log('处理时间键:', dateTimeKey, '记录数:', records.length)
				
				if (Array.isArray(records)) {
					records.forEach(record => {
						console.log('验证记录:', record)
						
						if (validateRainfallData(record)) {
							// 使用 dateTimeKey 作为时间基准
							let recordDate
							try {
								recordDate = new Date(dateTimeKey)
								// 检查日期是否有效
								if (isNaN(recordDate.getTime())) {
									console.warn('无效的日期格式:', dateTimeKey)
									return
								}
							} catch (error) {
								console.warn('日期解析失败:', dateTimeKey, error)
								return
							}
							
							const dateKey = recordDate.toISOString().split('T')[0]
							console.log('记录日期:', dateKey, '降雨量:', record.precipitation)
							
							if (!dailyStats[dateKey]) {
								dailyStats[dateKey] = 0
							}
							dailyStats[dateKey] += record.precipitation
							
							console.log('累计降雨量:', dateKey, dailyStats[dateKey])
						} else {
							console.log('记录验证失败:', record)
						}
					})
				}
			}
			
			console.log('每日统计数据:', dailyStats)
			
			// 生成近三日数据显示 - 从今天往前数3天
			const recentData = []
			// 从3天前开始，到今天，共3天的数据
			for (let i = 3; i >= 1; i--) {
				const date = new Date(today8AM.getTime() - i * 24 * 60 * 60 * 1000)
				const nextDate = new Date(date.getTime() + 24 * 60 * 60 * 1000)
				const dateKey = date.toISOString().split('T')[0]
				
				const startStr = `${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日 08时`
				const endStr = `${String(nextDate.getMonth() + 1).padStart(2, '0')}月${String(nextDate.getDate()).padStart(2, '0')}日 08时`
				
				const amount = dailyStats[dateKey] ? (Math.round(dailyStats[dateKey] * 10) / 10).toFixed(1) : '0.0'
				
				recentData.push({
					period: `${startStr} - ${endStr}`,
					amount: amount
				})
			}
			
			console.log('最终近三日数据:', recentData)
			recentRainfallData.value = recentData
		} else {
			console.error('API返回失败:', response.data)
			recentRainfallData.value = []
		}
	} catch (error) {
		console.error('获取近三日统计数据失败:', error)
		recentRainfallData.value = []
	}
}

// 返回上一页
const goBack = () => {
	uni.navigateBack({
		delta: 1
	})
}

// 组件挂载
onMounted(async () => {
	console.log('station-detail页面挂载，参数:', {
		stationCode: stationCode.value,
		stationName: stationName.value,
	})
	
	// 获取近三日雨量统计数据（仅用于上方统计显示）
	await getRecentRainfallData()
	
	// 等待DOM渲染完成
	await nextTick()
	
	// 页面加载时自动调用查询表格操作
	console.log('页面初始化完成，自动查询表格数据')
	await queryStationData()
})

// 初始化柱状图
const initRainfallBarChart = () => {
	// #ifdef H5
	nextTick(() => {
		// 增加延迟确保DOM完全渲染
		setTimeout(() => {
			console.log('initRainfallBarChart: 开始初始化柱状图')
			
			// 尝试多种方式获取canvas元素
			let canvas = null
			let ctx = null
			
			// 方法1: 直接通过ID获取
			canvas = document.getElementById('rainfall-line-chart')
			console.log('initRainfallBarChart: 方法1获取Canvas元素:', canvas)
		
		if (canvas && typeof canvas.getContext === 'function') {
			try {
				ctx = canvas.getContext('2d')
				console.log('initRainfallBarChart: 方法1成功获取上下文')
			} catch (error) {
				console.log('initRainfallBarChart: 方法1获取上下文失败:', error)
			}
		}
		
		// 方法2: 如果方法1失败，尝试查找内部的canvas元素
		if (!ctx && canvas) {
			const innerCanvas = canvas.querySelector('canvas')
			console.log('initRainfallBarChart: 方法2查找内部canvas:', innerCanvas)
			if (innerCanvas && typeof innerCanvas.getContext === 'function') {
				try {
					ctx = innerCanvas.getContext('2d')
					canvas = innerCanvas // 更新canvas引用
					console.log('initRainfallBarChart: 方法2成功获取上下文')
				} catch (error) {
					console.log('initRainfallBarChart: 方法2获取上下文失败:', error)
				}
			}
		}
		
		// 方法3: 直接查询所有canvas元素
		if (!ctx) {
			const allCanvas = document.querySelectorAll('canvas')
			console.log('initRainfallBarChart: 方法3找到所有canvas元素:', allCanvas.length)
			for (let i = 0; i < allCanvas.length; i++) {
				const canvasEl = allCanvas[i]
				if (canvasEl.id === 'rainfall-line-chart' || canvasEl.className.includes('rainfall-line-chart')) {
					try {
						ctx = canvasEl.getContext('2d')
						canvas = canvasEl
						console.log('initRainfallBarChart: 方法3成功获取上下文')
						break
					} catch (error) {
						console.log('initRainfallBarChart: 方法3获取上下文失败:', error)
					}
				}
			}
		}
		
		// 方法4: 如果还是失败，尝试通过类名查找
		if (!ctx) {
			const canvasByClass = document.querySelector('.rainfall-line-chart')
			console.log('initRainfallBarChart: 方法4通过类名查找canvas:', canvasByClass)
			if (canvasByClass && typeof canvasByClass.getContext === 'function') {
				try {
					ctx = canvasByClass.getContext('2d')
					canvas = canvasByClass
					console.log('initRainfallBarChart: 方法4成功获取上下文')
				} catch (error) {
					console.log('initRainfallBarChart: 方法4获取上下文失败:', error)
				}
			}
		}
		
		// 检查当前环境和DOM状态
		console.log('initRainfallBarChart: 当前环境检查:', {
			isH5: true,
			chartDataLength: chartData.value.length,
			documentReady: document.readyState,
			allCanvasCount: document.querySelectorAll('canvas').length,
			targetElement: document.getElementById('rainfall-line-chart')
		})
		
		if (!canvas || !ctx) {
			console.error('initRainfallBarChart: 无法获取有效的canvas元素和上下文')
			console.error('initRainfallBarChart: 调试信息:', {
				canvas: canvas,
				canvasType: typeof canvas,
				hasGetContext: canvas ? typeof canvas.getContext : 'N/A',
				chartScrollContainerExists: !!document.querySelector('.chart-scroll-container')
			})
			return
		}
		
		console.log('initRainfallBarChart: 柱状图数据:', chartData.value)
		console.log('initRainfallBarChart: 数据条数:', chartData.value.length)
			
			if (chartData.value.length === 0) {
				// 显示无数据提示
				ctx.fillStyle = '#666'
				ctx.font = '20px Arial'
				ctx.textAlign = 'center'
				ctx.fillText('暂无降雨数据', 1200, 200)
				return
			}
			
			// 清空画布 - 使用更宽的尺寸以支持横向滚动
			ctx.clearRect(0, 0, 2400, 400)
			
			// 设置画布尺寸 - 增加宽度以容纳更多数据点，支持横向滚动
			const chartWidth = 2400
			const chartHeight = 400
			const padding = { top: 30, right: 20, bottom: 80, left: 50 }
			const plotWidth = chartWidth - padding.left - padding.right
			const plotHeight = chartHeight - padding.top - padding.bottom
			
			// 准备数据 - 按时间正序排列用于绘制
			const sortedData = [...chartData.value].sort((a, b) => new Date(a.time) - new Date(b.time))
			console.log('initRainfallBarChart: 排序后的数据:', sortedData)
			
			// 计算最大值和最小值 - 只考虑有数据的值
			const rainfallValues = sortedData.filter(d => d.hasData && d.value !== null).map(d => d.value)
			const maxValue = rainfallValues.length > 0 ? Math.max(...rainfallValues, 0) : 0
			const minValue = rainfallValues.length > 0 ? Math.min(...rainfallValues, 0) : 0
			const valueRange = maxValue - minValue || 1 // 避免除零
			
			// 绘制背景
			ctx.fillStyle = '#ffffff'
			ctx.fillRect(0, 0, chartWidth, chartHeight)
			
			// 绘制网格线
			ctx.strokeStyle = '#f0f0f0'
			ctx.lineWidth = 1
			
			// 水平网格线
			const ySteps = 6
			for (let i = 0; i <= ySteps; i++) {
				const y = padding.top + (plotHeight / ySteps) * i
				ctx.beginPath()
				ctx.moveTo(padding.left, y)
				ctx.lineTo(padding.left + plotWidth, y)
				ctx.stroke()
			}
			
			// 垂直网格线
			const xSteps = Math.min(sortedData.length - 1, 12) // 最多12条垂直线
			for (let i = 0; i <= xSteps; i++) {
				const x = padding.left + (plotWidth / xSteps) * i
				ctx.beginPath()
				ctx.moveTo(x, padding.top)
				ctx.lineTo(x, padding.top + plotHeight)
				ctx.stroke()
			}
			
			// 绘制坐标轴
			ctx.strokeStyle = '#ddd'
			ctx.lineWidth = 2
			
			// Y轴
			ctx.beginPath()
			ctx.moveTo(padding.left, padding.top)
			ctx.lineTo(padding.left, padding.top + plotHeight)
			ctx.stroke()
			
			// X轴
			ctx.beginPath()
			ctx.moveTo(padding.left, padding.top + plotHeight)
			ctx.lineTo(padding.left + plotWidth, padding.top + plotHeight)
			ctx.stroke()
			
			// 绘制柱状图
			const totalBars = sortedData.length
			const availableWidth = plotWidth
			const barWidth = Math.max(6, Math.min(12, availableWidth * 0.6 / totalBars)) // 柱子占60%空间，最小6px，最大12px
			const totalBarWidth = totalBars * barWidth
			const totalSpacing = availableWidth - totalBarWidth
			const barSpacing = totalSpacing / (totalBars - 1) // 柱子之间的间距，不包括两端
			
			// 计算Y轴比例 - 基于最大值
			const yScale = plotHeight / (maxValue * 1.2) // 留20%的空间，增加顶部空间
			
			sortedData.forEach((item, index) => {
				// 修改X坐标计算，使柱子均匀分布在整个宽度内
				const x = padding.left + (index * (availableWidth - barWidth)) / (totalBars - 1)
				
				const barHeight = item.value * yScale
				const y = padding.top + plotHeight - barHeight
				
				// 绘制柱子阴影（更淡的阴影）
				ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
				ctx.fillRect(x + 1, y + 1, barWidth, barHeight)
				
				// 绘制柱子 - 使用蓝色系
				if (item.value > 0) {
					ctx.fillStyle = '#4A90E2' // 蓝色柱子
				} else {
					ctx.fillStyle = '#E8F4FD' // 浅蓝色表示无降雨
				}
				ctx.fillRect(x, y, barWidth, barHeight)
				
				// 绘制柱子边框（更细的边框）
				ctx.strokeStyle = 'rgba(74, 144, 226, 0.3)'
				ctx.lineWidth = 0.5
				ctx.strokeRect(x, y, barWidth, barHeight)
				
				// 绘制数值标签（只在有降雨时显示）
				if (item.value > 0) {
					ctx.fillStyle = '#333'
					ctx.font = 'bold 8px Arial' // 减小字体以适应更小的柱子
					ctx.textAlign = 'center'
					ctx.fillText(item.value.toFixed(1), x + barWidth / 2, y - 5)
				}
			})
		
		// 绘制Y轴标签
		ctx.fillStyle = '#666'
		ctx.font = '12px Arial'
		ctx.textAlign = 'right'
		const maxDisplayValue = maxValue * 1.2 // 与yScale计算保持一致
		for (let i = 0; i <= ySteps; i++) {
			const value = (maxDisplayValue / ySteps) * i
			const y = padding.top + plotHeight - (value / maxDisplayValue) * plotHeight
			ctx.fillText(value.toFixed(0), padding.left - 10, y + 4)
		}
		
		// 绘制X轴标签（时间）- 日期和小时分两行显示
		ctx.fillStyle = '#666'
		ctx.font = '10px Arial'
		ctx.textAlign = 'center'
		sortedData.forEach((item, index) => {
			// 使用与柱子相同的X坐标计算方式
			const x = padding.left + (index * (availableWidth - barWidth)) / (totalBars - 1) + barWidth / 2
			const date = new Date(item.time)
			
			// 第一行：日期（月-日）
			const dateStr = `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			ctx.fillText(dateStr, x, padding.top + plotHeight + 15)
			
			// 第二行：小时
			const hourStr = `${String(date.getHours()).padStart(2, '0')}时`
			ctx.fillText(hourStr, x, padding.top + plotHeight + 30)
		})
		
		// Y轴标题
		ctx.save()
		ctx.translate(20, padding.top + plotHeight / 2)
		ctx.rotate(-Math.PI / 2)
		ctx.textAlign = 'center'
		ctx.font = 'bold 12px Arial'
		ctx.fillStyle = '#333'
		ctx.fillText('降雨量 (mm)', 0, 0)
		ctx.restore()
		
		// X轴标题
		ctx.fillStyle = '#333'
		ctx.font = 'bold 12px Arial'
		ctx.textAlign = 'center'
		ctx.fillText('时间', padding.left + plotWidth / 2, chartHeight - 10)
		}, 300) // 闭合setTimeout函数
	})
	// #endif
}

// 监听chartData变化，更新折线图
watch(chartData, () => {
	nextTick(() => {
		// 延迟初始化，确保DOM完全渲染
		setTimeout(() => {
			initRainfallBarChart()
		}, 200)
	})
}, { deep: true })

</script>

<style scoped>
.station-detail {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	display: flex;
	align-items: center;
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
	padding: 10px 20px;
	color: white;
}

.header-left {
	margin-right: 15px;
	cursor: pointer;
}

.back-icon {
	font-size: 20px;
	font-weight: bold;
}

.header-center {
	flex: 1;
}

.station-name {
	font-size: 18px;
	font-weight: bold;
	display: block;
}

.station-code {
	font-size: 14px;
	opacity: 0.8;
	display: block;
	margin-top: 2px;
}

.info-card {
	background-color: white;
	margin: 10px 15px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px;
	border-bottom: 1px solid #f0f0f0;
}

.card-title {
	font-size: 16px;
	font-weight: bold;
	color: #333;
}

.update-time {
	font-size: 12px;
	color: #999;
}

.card-content {
	padding: 15px;
}

.recent-rainfall-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.rainfall-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px 0;
	border-bottom: 1px solid #f0f0f0;
}

.rainfall-item:last-child {
	border-bottom: none;
}

.rainfall-period {
	font-size: 14px;
	color: #666;
}

.rainfall-amount {
	font-size: 14px;
	color: #333;
}

/* 时间选择器样式 */
.simple-date-bar {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 20rpx;
	flex-wrap: wrap;
}

.date-separator {
	color: #7b8794;
	font-size: 26rpx;
	padding: 0 8rpx;
}

.data-table-section {
	border-top: 1px solid #f0f0f0;
	padding-top: 15px;
}

.table-header {
	display: flex;
	background-color: #f8f9fa;
	padding: 10px;
	border-radius: 4px;
	margin-bottom: 5px;
}

.table-title {
	flex: 1;
	font-size: 14px;
	font-weight: bold;
	color: #333;
	text-align: center;
}

.table-content {
	max-height: 200px;
	overflow-y: auto;
}

.table-row {
	display: flex;
	padding: 8px 10px;
	border-bottom: 1px solid #f0f0f0;
}

.table-row.even-row {
	background-color: #fafafa;
}

.table-cell {
	flex: 1;
	font-size: 12px;
	color: #666;
	text-align: center;
}

.empty-table {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100px;
	color: #999;
}

.empty-text {
	font-size: 14px;
}

/* 折叠展开控制条 */
.expand-bar {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 16rpx 20rpx;
	color: #7b8794;
	font-size: 20rpx;
	border-top: 1rpx dashed #e9edf3;
}
.expand-action { color: #2c7be5; }
.expand-arrow  { color: #9aa0a6; }


/* 折线图样式 */
.chart-scroll-container {
	width: 100%;
	height: 400px;
	overflow-x: auto;
	overflow-y: hidden;
	border: 2rpx solid #e9ecef;
	border-radius: 8rpx;
	background: #ffffff;
	position: relative;
	margin: 10px 0;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	/* 自定义滚动条样式 */
	scrollbar-width: thin;
	scrollbar-color: #007bff #f1f3f4;
}

/* 滚动提示 */
.chart-scroll-container::before {
	content: "← 可左右滑动查看更多数据 →";
	position: absolute;
	top: 5px;
	right: 10px;
	font-size: 24rpx;
	color: #666;
	background: rgba(255, 255, 255, 0.9);
	padding: 4rpx 8rpx;
	border-radius: 4rpx;
	z-index: 10;
	pointer-events: none;
}

/* Webkit浏览器滚动条样式 */
.chart-scroll-container::-webkit-scrollbar {
	height: 12px;
}

.chart-scroll-container::-webkit-scrollbar-track {
	background: #f1f3f4;
	border-radius: 6px;
}

.chart-scroll-container::-webkit-scrollbar-thumb {
	background: #007bff;
	border-radius: 6px;
	border: 2px solid #f1f3f4;
}

.chart-scroll-container::-webkit-scrollbar-thumb:hover {
	background: #0056b3;
}

.rainfall-line-chart {
	display: block;
	background-color: white;
	border-radius: 4px;
	height: 400px;
	width: 2400px; /* 固定宽度确保滚动 */
	cursor: grab; /* 显示可拖拽的光标 */
}

.rainfall-line-chart:active {
	cursor: grabbing; /* 拖拽时的光标 */
}

.chart-not-supported {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 300px;
	color: #999;
	font-size: 14px;
	background-color: #f9f9f9;
	border: 1px dashed #ddd;
	border-radius: 4px;
}
</style>